package com.xixilala.video.util

import android.content.Context
import com.xixilala.video.App
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception

object FileUtil {

    fun pcmFile(newFile:Boolean=false): File {
        val fileName = "audioRecord.pcm"
        val fileDir = App.appContext.cacheDir
        val file = File(fileDir, fileName)
        if (newFile && file.exists()) {
            file.delete()
            file.createNewFile()
        }
        return file
    }
    fun wavFile(newFile:Boolean=false) :File{
        val fileName = "audioRecord.wav"
        val fileDir = App.appContext.cacheDir
        val file = File(fileDir, fileName)
        if (newFile && file.exists()) {
            file.delete()
            file.createNewFile()
        }
        return file
    }

    fun getTestMp4(context: Context): File {
        return File(context.cacheDir,"test_video.mp4")
    }

    fun getTestOutputVideo(context: Context): File {
        val file = File(context.cacheDir, "test_video_output_video.mp4")
        file.deleteOnExit()
        file.createNewFile()
        return file
    }

    fun getTestOutputAudio(context: Context): File {
        val file = File(context.cacheDir, "test_video_output_audio.mp4a")
        file.deleteOnExit()
        file.createNewFile()
        return file
    }

    fun mp4Assets2CachePath(context: Context)  {
        val resultFile = File(context.cacheDir,"test_video.mp4")
        if (resultFile.exists()) {
            return
        }
        var isFailed = true
        try {
            resultFile.createNewFile()

            val fileIs = context.assets.open("test_video.mp4")

            val fos = FileOutputStream(resultFile)

            val buf = ByteArray(1024 * 4)
            var p: Int
            while (run {
                    p = fileIs.read(buf)
                    p
                } != -1) {
                fos.write(buf, 0, p)
            }
            isFailed = false

        } catch (e:Exception) {
            e.printStackTrace()
            isFailed = true
        } finally {
            if (isFailed) {
                resultFile.deleteOnExit()
            }
        }
    }
}